package com.kyomonn.talkischeap.DeepSeek;

import android.util.Log;

import androidx.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;

/**
 * 用于访问DeepSeek的API接口工具类
 */
public class DeepSeekClient {
    /** @noinspection SpellCheckingInspection*/
    private static final String API_KEY = "sk-51e34f65972446a08baac0c0b22db300";
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String MODEL = "deepseek-chat";    // DeepSeek-V3
    // private final String MODEL = "deepseek-reasoner";    // DeepSeek-R1
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();

    private static final List<JSONObject> messages = new ArrayList<>(); // 存储对话上下文

    /**
     * 发送消息到 DeepSeek API，并通过流式方式返回 AI 的回复
     *
     * @param userInput      用户输入的内容
     * @param streamCallback 流式数据回调接口
     */
    public static void sendMessageReplyStream(String userInput, StreamCallback streamCallback) {
        try {
            messages.add(new JSONObject().put("role", "user").put("content", userInput));

            // 构造请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", MODEL);
            requestBody.put("messages", new JSONArray(messages));
            requestBody.put("max_tokens", 1024);
            requestBody.put("temperature", 0.7);
            requestBody.put("stream", true); // 启用流式输出

            RequestBody body = RequestBody.create(requestBody.toString(), MediaType.get("application/json"));
            Request request = new Request.Builder()
                    .url(API_URL)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + API_KEY)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 发送请求并获取响应
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    if (!response.isSuccessful()) {
                        streamCallback.onError(new IOException("请求失败: " + response.code()));
                        return;
                    }

                    ResponseBody responseBody = response.body();
                    if (responseBody == null) {
                        streamCallback.onError(new IOException("响应体为空"));
                        return;
                    }

                    try (BufferedSource source = responseBody.source()) {
                        StringBuilder fullResponse = new StringBuilder();
                        while (!source.exhausted()) {
                            String line = source.readUtf8Line();
                            if (line != null && line.startsWith("data: ")) {
                                String jsonData = line.substring(6); // 去除"data: "前缀
                                if (!jsonData.equals("[DONE]")) {
                                    try {
                                        JSONObject json = new JSONObject(jsonData);
                                        String content = json.getJSONArray("choices")
                                                .getJSONObject(0)
                                                .getJSONObject("delta")
                                                .getString("content");
                                        fullResponse.append(content);
                                        streamCallback.onTokenReceived(content); // 回调每段数据
                                    } catch (Exception ignored) {
                                        // 忽略无法解析的数据块
                                    }
                                }
                            }
                        }

                        // 记录 AI 回复到对话历史
                        messages.add(new JSONObject().put("role", "assistant").put("content", fullResponse.toString()));

                        // AI回复完成，调用完成回调
                        streamCallback.onCompleted();
                    } catch (IOException | JSONException e) {
                        streamCallback.onError(e);
                    }
                }

                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    streamCallback.onError(e);
                }
            });
        } catch (Exception e) {
            Log.e("MyTag", e.toString());
            streamCallback.onError(e);
            streamCallback.onTokenReceived("服务器繁忙，请稍后再试。");
        }
    }
}
